<template>
    <div>
      <Portlet title="报亏单详情">
        <el-form label-position="left" label-width="100px">
          <el-row>
            <el-col :lg="6" :md="12">
              <el-form-item label="报亏单编号："> <span>{{ headerDetail.gainorlossNo }}</span></el-form-item>
            </el-col>
            <el-col :lg="6" :md="12">
              <el-form-item label="创 建 人："> <span>{{ headerDetail.founderUserName }}</span> </el-form-item>
            </el-col>
            <el-col :lg="6" :md="12">
              <el-form-item label="创建时间："> <span>{{ headerDetail.foundtime|unixTimestampFilter }}</span></el-form-item>
            </el-col>
            <el-col :lg="6" :md="12">
              <el-form-item label="报亏单来源："> <span> {{ headerDetail.gainorlossSource|filterResource }}</span> </el-form-item>
            </el-col>
            <el-col :lg="6" :md="12" v-if="state == 1">
              <el-form-item label="审 核 人："> <span>{{ headerDetail.auditorName }}</span> </el-form-item>
            </el-col>
            <el-col :lg="6" :md="12" v-if="state == 1">
              <el-form-item label="审核时间："> <span>{{ headerDetail.auditTime|unixTimestampFilter }}</span></el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </Portlet>
      <Portlet title="货物信息">
        <!--含表单的table-->
        <el-row v-if="state == 0">
          <el-col :span="24">
            <el-form :model="model" :rules="rules" label-position="left" ref="elForm" label-width="100px">
              <el-form-item label-width="0" prop="locationPackageBean" :rules="[
                  {required: true, message: '货物信息必须', trigger: 'change', type: 'array'}
               ]">
                <el-table :data="model.locationPackageBean"
                          style="width:100%"
                          border
                          max-height="500"
                          class="text-center"
                >
                  <!--show-summary-->
                  <!--:summary-method="getSum"-->
                  <el-table-column
                    label="序号"
                    align="center"
                    type="index"
                    max-width="40">
                  </el-table-column>
                  <el-table-column
                    align="center"
                    min-width="90"
                    prop="cargoOwnerName"
                    label="商家名称"
                  >
                  </el-table-column>
                  <el-table-column
                    align="center"
                    min-width="90"
                    prop="locationName"
                    label="所在库位">
                  </el-table-column>
                  <el-table-column
                    align="center"
                    min-width="90"
                    prop="productName"
                    label="所属产品">
                  </el-table-column>
                  <el-table-column
                    align="center"
                    min-width="90"
                    prop="productNo"
                    label="产品编号">
                  </el-table-column>
                  <el-table-column
                    align="center"
                    max-width="200"
                    prop="packageName"
                    label="包件名称">
                  </el-table-column>
                  <el-table-column
                    align="center"
                    min-width="120"
                    prop="packageCode"
                    label="包件编号">
                  </el-table-column>

                  <el-table-column
                    align="center"
                    max-width="80"
                    prop="locationPackageNum"
                    label="在库包件数量">
                  </el-table-column>
                  <el-table-column
                    max-width="80"
                    align="center"
                    prop="gainorlossNum"
                    label="报亏包件数量">
                  </el-table-column>
                  <el-table-column
                    align="center"
                    min-width="120"
                    label="通过审核数量">
                    <template slot-scope="scope">
                      <el-form-item label-width="0" :prop="'locationPackageBean.' + scope.$index + '.auditNum'" :rules="[
                          {required: true, message: '通过审核数量必须', trigger: 'blur'},
                          {validator: range, min: 0, message: '请输入大等于0的正数', trigger: 'blur'},
                          {validator: isInteger, message: '请输入整数数字！', trigger: 'blur'},
                          {validator: range, max: scope.row.locationPackageNum, message: '不能够超过在库包件数量', trigger: 'blur'}
                       ]">
                        <!--<el-input-number v-model="scope.row.auditNum" :min="0" :max="99999" label="描述文字"></el-input-number>-->
                        <el-input style="width:88%" :maxlength="200" v-model="scope.row.auditNum"/>
                      </el-form-item>
                    </template>
                  </el-table-column>

                  <el-table-column
                    min-width="180"
                    align="center"
                    label="责任人">
                    <template slot-scope="scope">
                      <el-form-item :prop="'locationPackageBean.' + scope.$index + '.responsiblePerson'" :rules="[
                          {required: true, message: '责任人必须', trigger: 'change'}
                       ]">
                        <!--<el-input style="width:88%" :maxlength="200" v-model="scope.row.responsiblePersonName"/>-->

                        <el-select filterable style="width: 90%" v-model="scope.row.responsiblePerson" placeholder="可搜索查询">
                          <el-option v-for="item of personArr" :label="item.text" :value="item.value" :key="item.value"></el-option>
                        </el-select>

                      </el-form-item>
                    </template>
                  </el-table-column>

                  <el-table-column
                    min-width="180"
                    align="center"
                    label="报亏备注">
                    <template slot-scope="scope">
                      <el-form-item label-width="0" :prop="'locationPackageBean.' + scope.$index + '.gainorlossMemo'">
                        <el-input style="width:88%; text-align: left " :maxlength="200" v-model="scope.row.gainorlossMemo"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
                <p>
                  <el-row>
                    <el-col :span="2">
                      <el-form-item>
                        <span style="font-weight: 800;line-height: 40px;">审核备注：</span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="22">
                      <el-form-item prop="auditMemo"
                                    :rules="[
                                {required: true, message: '审核备注必须', trigger: 'change'}
                              ]"
                      >
                        <el-input :maxlength="50" v-model="model.auditMemo"/>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row style="margin-top:15px;">
                    <el-col :span="2" :offset="10">
                      <el-button :loading="loading" class="btn-block" @click.prevent="submit" type="primary">提交审核</el-button>
                    </el-col>
                  </el-row>
                </p>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <!--纯展示：已审核的详情table-->
        <el-row v-if="state == 1">
          <el-col :span="24">
            <el-table
              border
              max-height="500"
              :data="showDataTable"
              class="text-center"
            >
              <!--:summary-method="getSummaries"-->
              <!--show-summary-->
              <el-table-column
                align="center"
                label="序号"
                type="index"
                width="55">
              </el-table-column>
              <el-table-column
                align="center"
                prop="cargoOwnerName"
                label="商家名称"
              >
              </el-table-column>
              <el-table-column
                align="center"
                prop="locationName"
                width="110px"
                label="所在库位">
              </el-table-column>
              <el-table-column
                align="center"
                prop="productName"
                width="250px"
                label="所属产品">
              </el-table-column>
              <el-table-column
                align="center"
                prop="productNo"
                width="205px"
                label="产品编号">
              </el-table-column>
              <el-table-column
                prop="packageName"
                align="center"
                width="185px"
                label="包件名称">
              </el-table-column>
              <el-table-column
                prop="packageCode"
                align="center"
                label="包件编号">
              </el-table-column>
              <el-table-column
                prop="locationPackageNum"
                align="center"
                label="在库包件数量">
              </el-table-column>
              <el-table-column
                prop="gainorlossNum"
                align="center"
                label="报亏包件数量">
                <template slot-scope="scope">
                  <span>{{scope.row.gainorlossNum}}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="responsiblePersonName"
                label="责任人">
              </el-table-column>
              <el-table-column
                align="center"
                prop="gainorlossMemo"
                label="报亏备注">
              </el-table-column>
              <slot></slot>
            </el-table>
            <p>
              <el-col :span="24">
                <span style="margin-right:15px;"> 审核备注：</span> <span>{{headerDetail.auditMemo}}</span>
              </el-col>
            </p>
            <Pagination style="margin-top: 20px" class="pull-right"
                        :total-item="totalItem"
                        @pagination="pagination"
                        :perItem="params.pageSize" :page.sync="params.pageNum"
                        @sizeChange="sizeChange"></Pagination>
          </el-col>

        </el-row>
      </Portlet>
    </div>
</template>
<script>
import {unixTimestampFilter} from '@/filters'
import {dotData, copy, alert} from '@/utils'
import {range, isInteger} from '@/utils/validate'
import {getAccounts} from '@/utils/selectOptions'
import Pagination from '@/components/Pagination'
export default {
  name: 'lossReportShow',
  components: {
    Pagination
  },
  filters: {
    unixTimestampFilter,
    filterResource(value) {
      switch (value) {
        case 1: return '手动创建'
        case '1': return '手动创建'
        case 2: return '盘库'
        case '2' : return '盘库'
        default: return '未知'
      }
    }
  },
  data() {
    return {
      id: this.$route.params.id,
      state: this.$route.query.state,
      headerDetail: {}, // 头部信息
      personArr: [], // 模糊搜索 字典
      backArr: [],
      loading: false,
      model: {
        locationPackageBean: [],
        auditMemo: ''
      },
      showDataTable: [],
      warehouseIdArr: [],
      rules: {},
      restaurants: [],
      cargoOwnerArr: [], // 模拟 库位下拉选项
      params: {
        pageSize: 20,
        pageNum: 1
      },
      totalItem: 0
    }
  },
  created() {
    // 责任人
    getAccounts().then(arr => {
      this.personArr = arr || []
    })
    // 获取头部
    if (this.id) {
      this.httpHeader()
    }
    // 获取包件
    this.httpGetPackage()
  },
  methods: {
    range,
    isInteger,
    // 翻页
    pagination(page) {
      this.params.pageNum = page
      this.httpGetPackage()
    },
    // 每页几条
    sizeChange(size) {
      this.params.pageSize = size
      this.httpGetPackage()
    },
    httpHeader() {
      this.$ajax.get('/ms-warehouse-order/inventory/findGainOrLossDetail', {id: this.id}).then(response => {
        if (response.success) {
          this.headerDetail = dotData(response, 'data')
          console.log('请求回来的头部信息', this.headerDetail)
        }
      })
    },
    // table详情
    httpGetPackage() {
      this.params.id = this.id
      this.$ajax.table('/ms-warehouse-order/inventory/findGainOrLossItem', this.params).then(response => {
        this.totalItem = response.totalItem
        this.showDataTable = response.data || []
        this.backArr = response.data
        // 数组里 新加字段，并赋初始值
        this.backArr.forEach(k => {
          this.$set(k, 'gainOrLossItemId', k.id) // 新建 包件id字段，存该行的id
          this.$set(k, 'auditNum', k.gainorlossNum) // 新建 通过审核数量
          this.$set(k, 'gainorlossMemo', k.gainorlossMemo) // 报亏备注：初始化 默认值
          this.$set(k, 'responsiblePerson', k.responsiblePerson) // 负责人id：初始化
        })
        this.model.locationPackageBean = this.backArr
        console.log('0000', this.model.locationPackageBean)
      })
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        let data = copy(this.model, true)
        // 删除数组中每行里 多余的字段
        let tempArr = []
        if (Array.isArray(data.locationPackageBean)) {
          data.locationPackageBean.forEach(v => {
            tempArr.push({
              gainOrLossItemId: v.gainOrLossItemId,
              auditNum: v.auditNum,
              responsiblePerson: v.responsiblePerson,
              gainorlossMemo: v.gainorlossMemo
            })
          })
        }
        data.locationPackageBean = tempArr // 覆盖为新数组
        data.gainorlossState = 2 // '报亏'
        data.gainOrLossId = this.id // 报亏订单号
        let url = '/ms-warehouse-order/inventory/auditGainOrLoss'
        console.log('postData', data)
        this.$confirm('<p>审核提交后，该库位上的在库包件数量</p><p>将根据通过审核的数量相应的减少库存</p>', '温馨提示', {
          type: 'warning',
          center: true,
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            instance.confirmButtonLoading = false
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confrimButtonText = '提交中...'
              this.$ajax.post(url, data).then(response => {
                const success = dotData(response, 'success')
                if (success) {
                  done()
                  instance.confirmButtonLoading = false
                  setTimeout(() => {
                    this.$confirm('已提交审核', '已提交', {
                      type: 'success',
                      center: true,
                      confirmButtonText: '确定',
                      showCancelButton: false,
                      closeOnClickModal: false
                    }).then(_ => {
                      this.$router.push({path: '/ss-oms/warehouse/loss-report/index'})
                    })
                  }, 1000)
                } else {
                  done()
                  instance.confirmButtonLoading = false
                  setTimeout(() => {
                    this.$message({
                      type: 'error',
                      message: `提交失败`
                    })
                  }, 500)
                }
              })
            } else { done() }
          }
        })
      })
    }
  }
}
</script>
